<template>
  <div class="v-container">
    <v-header title="登录">
      <span class="back" @click="goBack">
        <i class="el-icon-arrow-left"></i>
      </span>
    </v-header>
    <div class="mt">
      <img src="@/assets/images/login_img.jpg" width="100%">
      <div class="login-box">
        <div class="login-title">请输入登录信息</div>
        <ul class="itemList">
          <li>
            <mt-field class="iconImg" placeholder="请输入手机号" v-model="telphone">
              <img class="iconImgg" src="@/assets/images/lg_tel.png" width="20">
            </mt-field>
          </li>
          <li v-if="showvCode">
            <mt-field class="iconImg" placeholder="请输入图形验证码" v-model="vCode">
              <img class="iconImgg" src="@/assets/images/lg_pass.png" width="20">
              <img :src="vCodeImg" width="80" alt="图形验证码" @click="updateCode">
            </mt-field>
          </li>
          <li>
            <mt-field class="iconImg" placeholder="请输入验证码" v-model="dCode">
              <img class="iconImgg" src="@/assets/images/lg_pass.png" width="20">
              <count-down ref="countDown" val="发送验证码" :count="120" v-on:do-count="sendCode"></count-down>
            </mt-field>
          </li>
        </ul>
      </div>
      <div class="button-box" v-on:click="submit">
        <p>登录</p>
      </div>
    </div>
  </div>
</template>

<script>
import vHeader from "@/components/Header.vue";
import countDown from "@/components/CountDown.vue";
import { Toast } from "mint-ui";
import { Resource } from "@/services/resource";
import LocalStorage from "@/services/storage";

export default {
  name: "login",
  components: {
    vHeader,
    countDown
  },
  props: {
    title: {
      type: String,
      default: "标题"
    }
  },
  data() {
    return {
      msg: "Footera",
      showvCode: false,
      telphone: "",
      dCode: "",
      vCode: null,
      vCodeImg: ""
    };
  },
  mounted() {
    let isWx=this.is_weixn();
    let openid = LocalStorage.getLocalStorage('openid');
    if(isWx){
      if(!openid){
        let code = getUrlParam("code");
        if(code == null || code === ''){
          var local = window.location.href;
          Resource.getAppId
          .post({}, {})
          .then(res => {
            if (res.head.resultCode == "000000") {
              let appid = res.body.appId;
              window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+
              "&redirect_uri="+encodeURIComponent(local)+"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
          
            }
          })
        }else{
          Resource.getOpenId
          .post({}, {"code": code})
          .then(res => {
            if (res.head.resultCode == "000000") {
              let openid = res.body.openId;
              LocalStorage.setLocalStorage(
                "openid",
                openid,
                90 * 24 * 60 * 60 * 1000
              );
            }
          })
        }
      }
    }
  },
  methods: {
    getUrlParam(name){
      var reg = new RegExp('(^|&)'+name+'=([^&]*)(&|$)');
      var r = window.location.search.substr(1).match(reg);
      if(r!=null){
        return unescape(r[2]);
      }
      return null;
    },
    is_weixn(){
      var ua = navigator.userAgent.toLowerCase(); 
      return ua.match(/MicroMessenger/i)=='micromessenger';
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    sendCode() {
      if (this.telphone === "") {
        Toast({
          message: "手机号不能为空",
          position: 'middle'
        });
      } else if (!/^1\d{10}$/i.test(this.telphone)) {
        Toast({
          message: "手机号码不符合要求",
          position: 'middle'
        });
      } else {
        this.$refs.countDown.isDisabled = true;
        Resource.getCheckCode
          .post({}, { telephone: this.telphone })
          .then(res => {
            if (res.head.resultCode == "SUCCESS") {
              //已发送
              this.$refs.countDown.setRemainTime();
              Toast({
                message: "发送成功",
                iconClass: "el-icon-success"
              });
            } else {
              this.$refs.countDown.isDisabled = false;
              Toast({
                message: res.head.resultMsg,
                position: 'middle'
              });
            }

            console.log(res);
          })
          .catch(err => {
            this.$refs.countDown.isDisabled = false;
            console.log(err);
          });
      }
    },
    submit() {
      // this.$router.push('/');
      if (this.telphone === "") {
        Toast({
          message: "手机号不能为空",
          position: 'middle'
        });
      } else if (!/^1\d{10}$/i.test(this.telphone)) {
        Toast({
          message: "手机号码不符合要求",
          position: 'middle'
        });
      } else if (this.dCode === "") {
        Toast({
          message: "验证码不能为空",
          position: 'middle'
        });
      } else {
        let openid = LocalStorage.getLocalStorage('openid');
        if(!openid){
          openid="";
        }
        Resource.login
          .post({}, { openId:openid,telephone: this.telphone, checkCode: this.dCode })
          .then(res => {
            console.log(res);
            if (res.head.resultCode == "000000") {
              let matrixContent = res.body.matrixContent;
              let token = res.head.token;

              LocalStorage.setLocalStorage(
                "loginStatus",
                matrixContent,
                90 * 24 * 60 * 60 * 1000
              );
              LocalStorage.setLocalStorage(
                "token",
                token,
                59 * 60 * 1000
              );
              this.$store.dispatch("login", token);

              let loginStatus = LocalStorage.getLocalStorage('loginStatus');
              Resource.userInfo
                .post({}, { matrixContent: loginStatus,needToken:true })
                .then(res => {
                  console.log(res)
                  LocalStorage.setLocalStorage(
                    "userInfo",
                    JSON.stringify(res.body),
                    90 * 24 * 60 * 60 * 1000
                  );
                  if (res.head.resultCode == "000000") {
                    if (res.body.carId == "" || res.body.carId == null) {
                      this.$router.push("/moreInformation");
                    } else if(res.body.serviceEndTime == '' || res.body.serviceEndTime == null) {
                      this.$router.replace('/');
                    } else {
                      this.$router.replace('/mainpage');
                    }


                  } else {
                    Toast({
                      message: res.head.resultMsg,
                      position: 'middle'
                    });
                  }
                });

              if (this.$route.query.redirect) {
                this.$router.replace({ path: this.$route.query.redirect });
              } else {
                this.$router.replace("/");
              }
            } else {
              this.$refs.countDown.isDisabled = false;
              Toast({
                message: res.head.resultMsg,
                position: 'middle'
              });
            }
          });
      }
    },
    // 更新图形验证码
    updateCode() {
      Resource.getRandomVCode
        .get({ time: new Date().getTime() }, { responseType: "blob" })
        .then(res => {
          const myBlob = res;
          this.vCodeImg = URL.createObjectURL(myBlob);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
};
</script>

<style lang="less" scoped>
@import url("./login.less");
</style>
<style scoped>
li >>> .mint-field-other {
  position: static;
}
</style>